#!/bin/bash

set -e

cd "$(dirname "$0")/.."

function clone_repo {
  owner=$1
  name=$2
  sha=$3

  path=examples/$name
  if [ ! -d "$path" ]; then
    echo "Cloning $owner/$name"
    git clone "https://github.com/$owner/$name" "$path"
  fi

  pushd "$path" > /dev/null
  head=$(git rev-parse HEAD)
  if [ "$head" != "$sha"  ]; then
    echo "Updating $owner/$name from $head to $sha"
    git fetch
    git reset --hard $sha
  fi
  popd > /dev/null
}

clone_repo 0install 0install 225587eef889a3082e0cc53fa64500f56cca0028
clone_repo BinaryAnalysisPlatform bap 0e3966ae027c72f0e1f2463afd132d9f10821d40
clone_repo dbuenzli cmdliner b2f03ea0427feaae59e2a0e02ff020f0d78ccbcf
clone_repo facebook flow 30855cad7ee6e6117b2b495d005ee95e1a11f9b4
clone_repo facebook pyre-check e73ca136a9d7150ea4606505ee3d732e227ddd83
clone_repo garrigue lablgtk 7e41440382b064bf3cf40f6efff493ce05250a84
clone_repo janestreet base a2b9340b5b2bf8df935422d14e03e497e6e8c98f
clone_repo mirage ocaml-cohttp 16e991ec1f7e5f0c99615cd1f58b99b02e3d0499
clone_repo ocaml dune e7a1d844ddf4ac8cfc82f6dfa1657799d338a9b6
clone_repo ocaml merlin 8f1d3f1be970663495a21b83c66bac9934351c82
clone_repo ocaml ocaml d9547617e8b14119beacafaa2546cbebfac1bfe5
clone_repo ocaml ocaml-lsp e81d16a72a4dceaf2e28fefe7db40b6553e3d4e7
clone_repo ocaml opam f539e4c6fb00f3aabcb5ed10bbe1d1e49dd2abb7
clone_repo ocaml-ppx ocamlformat 3d62b5841f2777642e8a0e34422a0a55667b3a67
clone_repo ocaml-ppx ppxlib e9077667078f55e8a67f1406691c450b30e5a6ba
clone_repo ocsigen js_of_ocaml e1fe3e955c30cb8b305cb1b65b1eaa4c700267b1
clone_repo ocsigen lwt cc05e2bda6c34126a3fd8d150ee7cddb3b8a440b
clone_repo owlbarn owl 48434ea744d8e5f488a56bb06ecd15659c58f186

known_failures="$(cat script/known_failures.txt)"

tree-sitter parse -q \
  'examples/**/*.ml' \
  'examples/**/*.mli' \
  $(for failure in $known_failures; do echo "!${failure}"; done)

example_count=$(find examples -name '*.ml' -o -name '*.mli' | wc -l)
failure_count=$(wc -w <<< "$known_failures")
success_count=$(( $example_count - $failure_count ))
success_percent=$(bc -l <<< "100*${success_count}/${example_count}")

printf \
  "Successfully parsed %d of %d example files (%.1f%%)\n" \
  $success_count $example_count $success_percent
